//
//  UserInfoViewController.m
//  UniversalApp
//
//  Created by 志刚杨 on 2018/2/9.
//  Copyright © 2018年 voidcat. All rights reserved.
//

#import "UserInfoViewController.h"

#import "CYToolBar.h"
#import "XMNShareMenu.h"
#import "userinfoHeaderTableViewCell.h"
#import "UserinfoVideoTableViewCell.h"
#import "UserPhotoTableViewCell.h"
#import "UserInfoGiftTableViewCell.h"
#import "UserPageInfoModel.h"
#import "UserInfoLogic.h"
#import "CustomChatUIViewController.h"
#import "LiveRoomViewController.h"
#import "CallUserViewController.h" //呼叫页面
#import "PrivatePhotosViewController.h" //私照
#import "VideoPlayViewController.h"
#import "ReportViewController.h"
#import "ContributionListViewController.h"
#import "ShareView.h"
#import "InviteLogic.h"
#import "TagHeaderTableViewCell.h"
#import "TagListTableViewCell.h"
#import "CallDataLogic.h"
#import "MSGOnSender.h"
#import "CallUserManger.h"
@interface UserInfoViewController
()<CYStatusToolbarDelegate,QMUITableViewDelegate,QMUITableViewDataSource,UserInfoLogicDelegate,LiveRoomVCDelegate,UserPageInfoModelDelegate>
{
    NSArray *_dataSource;
    NSArray *_listArray;
    UserInfoLogic *_logic;
    UserPageInfoModel *_model;//本页的数据
    NSInteger   _page;//分页页数
    CallDataLogic *_callDataLogic;
    NSMutableArray *_evaluateData;
}
@property(nonatomic, strong) InviteLogic *InviteLogic;

@end

@implementation UserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _logic = [UserInfoLogic new];
    _logic.uid = self.uid;
    _logic.delegagte = self;
    [[HUDHelper sharedInstance] syncLoading];
    [_logic loadData];
    [self createUI];
    [self setToolbarAndNav];
    
    [_logic getUserInfoWithUID:self.uid];
}

-(void)setToolbarAndNav
{
    QMUIButton *back = [[QMUIButton alloc] init];
    [back setImage:IMAGE_NAMED(@"mine_home_back") forState:UIControlStateNormal];
    back.frame = CGRectMake(0,20, 60, 60);
    [back addTarget:self action:@selector(handleBackEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:back];
    
    //分享按钮
    QMUIButton *shareButton = [[QMUIButton alloc] init];
    [shareButton setImage:IMAGE_NAMED(@"mine_home_share") forState:UIControlStateNormal];
    shareButton.frame = CGRectMake(SCREEN_WIDTH - 90,20, 60, 60);
    [shareButton addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:shareButton];
    
    //更多按钮
    QMUIButton *moreButton = [[QMUIButton alloc] init];
    [moreButton setImage:IMAGE_NAMED(@"mine_home_more") forState:UIControlStateNormal];
    moreButton.frame = CGRectMake(SCREEN_WIDTH - 50,20, 60, 60);
    [moreButton addTarget:self action:@selector(clickMore) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:moreButton];
    
    CYToolBar *toolbar = [[CYToolBar alloc]init];
    toolbar.backgroundColor = KWhiteColor;
    
    toolbar.frame =CGRectMake(0, SCREEN_HEIGHT - kTabBarHeight, self.view.bounds.size.width, kTabBarHeight);
    
//    if (@available(iOS 11.0,*)){
//        toolbar.bottom -= self.view.safeAreaInsets.bottom;
//    }
    toolbar.delegate = self;
    [self.view addSubview:toolbar];
}


#pragma mark ————— 创建页面 —————
-(void)createUI{
    self.tableView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.00];
    self.tableView.height = KScreenHeight - kTabBarHeight;
    self.tableView.mj_header.hidden = YES;
    self.tableView.separatorColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.00];
    self.tableView.mj_footer.hidden = YES;
    self.tableView.frame = self.view.bounds;
    self.tableView.height -= kTabBarHeight;
    
    //注册头部
    [self.tableView registerNib:[UINib nibWithNibName:[userinfoHeaderTableViewCell className] bundle:nil] forCellReuseIdentifier:[userinfoHeaderTableViewCell className]];
    
    //注册礼物
    [self.tableView registerNib:[UINib nibWithNibName:[UserInfoGiftTableViewCell className] bundle:nil] forCellReuseIdentifier:[UserInfoGiftTableViewCell className]];
    
    //小视频
    [self.tableView registerNib:[UINib nibWithNibName:[UserinfoVideoTableViewCell className] bundle:nil] forCellReuseIdentifier:[UserinfoVideoTableViewCell className]];
    
    //注册私照
    [self.tableView registerNib:[UINib nibWithNibName:[UserPhotoTableViewCell className] bundle:nil] forCellReuseIdentifier:[UserPhotoTableViewCell className]];
    
    //注册标签
    [self.tableView registerNib:[UINib nibWithNibName:[TagHeaderTableViewCell className] bundle:nil] forCellReuseIdentifier:[TagHeaderTableViewCell className]];
    [self.tableView registerNib:[UINib nibWithNibName:[TagListTableViewCell className] bundle:nil] forCellReuseIdentifier:[TagListTableViewCell className]];

    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    NSArray *l1 = [NSArray arrayWithObjects:ASLocalizedString(@"头部"), nil];
    NSArray *l51 = [NSArray arrayWithObjects:ASLocalizedString(@"用户印象"), nil];
    NSArray *l52 = [NSArray arrayWithObjects:ASLocalizedString(@"标签列表"), nil];
    NSArray *l2 = [NSArray arrayWithObjects:ASLocalizedString(@"收到的礼物"), nil];
//    NSArray *l3 = [NSArray arrayWithObjects:ASLocalizedString(@"小视频"), nil];
    NSArray *l4 = [NSArray arrayWithObjects:ASLocalizedString(@"私照"), nil];
    _listArray = [NSArray arrayWithObjects:l1,l2,l4,l51,l52,nil];
    [self.view addSubview:self.tableView];
    [self.tableView reloadData];
}
#pragma mark - tool点击回调
-(void)composeTool:(CYToolBar *)toolbar didClickedButton:(HMComposeToolbarButtonType)buttonType
{
    switch (buttonType) {
        case HMComposeToolbarleft:
            [self jumpChatUI];
            break;
        case HMComposeToolbarButtonTypemodel:
            [self gotoVideo];
            break;
        default:
            [self jumpChatUI];
            break;
    }
}


-(void)jumpChatUI
{
    self.isHidenNaviBar = NO;
    IMAUser *user = [[IMAUser alloc] initWith:self.uid];
    CustomChatUIViewController *vc = [[CustomChatUIViewController alloc] initWith:user];
    [self.navigationController pushViewController:vc animated:NO];
}

-(void)gotoVideo
{
    [[CallUserManger sharedCallUserManger] CallUserV2WithUid:self.uid ViewControler:self];
    return;
//    请求呼叫某用户
    
    
    //新接口
//    http://test0813.anbig.com/mapi/public/index.php/api/video_call_api/video_call_0907?uid=100171&token=8c5a7f200be783b4ea73caf908805eeb&id=100172
    
    //{"channel":"1539657504100171833","conversationDesc":"","deviceType":"Android","otherUserMsg":false,"sender":{"address":"济南市","avatar":"http://p4ulgsz1p.bkt.clouddn.com/20e4b201808161406222726.jpg","id":"100171","is_open_do_not_disturb":"0","is_reg_perfect":1,"sex":1,"token":"","user_nickname":".","user_sign":""},"type":12}
    
    [[HUDHelper sharedInstance] syncLoading];
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"video_call_api" A:@"video_call_0907"];

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.uid forKey:@"id"];
    [CYNET POST:url parameters:param responseCache:^(id responseObject) {

    } success:^(id responseObject) {
        NSString *channel_id = [responseObject valueForKey:@"channel_id"];
        Sender *sender = [Sender modelWithJSON:[responseObject valueForKey:@"to_user_base_info"]];
        VMsgMessage *vmessage = [[VMsgMessage alloc] init];
        vmessage.channel = channel_id;
        vmessage.sender = sender;
        vmessage.type = ReceiveCall;
        [[MSGOnSender new] pushCallMessage:vmessage Uid:self.uid];

        [[HUDHelper sharedInstance] syncStopLoading];
        //跳转到视频界面
        CallUserViewController *callView = [CallUserViewController new];
        callView.usermodel = _logic.model;
        callView.channel = [responseObject valueForKey:@"channel_id"];
        callView.iscall = YES;
        [self.navigationController pushViewController:callView animated:NO];

    } failure:^(NSString *error) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [MBProgressHUD showTopTipMessage:error];
    } hasCache:NO];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.isHidenNaviBar = YES;
    _callDataLogic = [[CallDataLogic alloc] init];
    _page = 1;
    [_callDataLogic getUserEvaluateListWhthUid:self.uid AndPage:StringFromInt(_page) Block:^(id selfPtr) {
        _evaluateData = [NSMutableArray arrayWithArray:selfPtr];
        [self.tableView reloadData];
    }];
    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.isHidenNaviBar = NO;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

#pragma mark - 视频代理回调
-(void)liveVCNeedClose:(LiveRoomViewController *)liveVC
{
    
}

#pragma mark - 数据加载完成回调
-(void)requestDataCompleted
{
    [[HUDHelper sharedInstance] syncStopLoading];
    [self.tableView reloadData];
    if ((_logic.model.sex == curUser.sex) && (![_logic.model.id isEqualToString:curUser.id])) {
        [MBProgressHUD showTopTipMessage:@"不能查看同性资料"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:NO];
        });
    }
}

#pragma mark ————— tableview 代理 —————
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    NSString *cellName = [_listArray objectAtIndex:section];
    if(_listArray.count != 0 && section == _listArray.count - 1)
    {
        return _evaluateData.count;
    }
    
    return [[_listArray objectAtIndex:section] count];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _listArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(_listArray.count != 0 && indexPath.section == _listArray.count - 1)
    {
        return 50;
    }
    NSString *cellName = [[_listArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    if([cellName isEqualToString:ASLocalizedString(@"头部")])
    {
        return KScreenWidth + 50;;
    }
    
    if([cellName isEqualToString:ASLocalizedString(@"收到的礼物")] || [cellName isEqualToString:ASLocalizedString(@"小视频")] || [cellName isEqualToString:ASLocalizedString(@"私照")])
    {
        return 100;
    }

    
    return 50.0f;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(_listArray.count != 0 && indexPath.section == _listArray.count - 1)
    {
        TagListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[TagListTableViewCell className]];
        cell.model = _evaluateData[indexPath.row];
        return cell;
    }
    
    NSString *cellName = [[_listArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    if([cellName isEqualToString:ASLocalizedString(@"头部")])
    {
        userinfoHeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[userinfoHeaderTableViewCell className]];
        
        kWeakSelf(self);
        [cell.ContributionList addTapBlock:^(UIButton *btn) {
            ContributionListViewController *vc = [[ContributionListViewController alloc] init];
            vc.touid = weakself.uid;
            [weakself.navigationController pushViewController:vc animated:YES];
        }];
        
        [cell setModel:_logic.model];
        return cell;
    }
    
    if([cellName isEqualToString:ASLocalizedString(@"贡献榜")])
    {
        UserPhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[UserPhotoTableViewCell className]];
        return cell;
    }
    
    if([cellName isEqualToString:ASLocalizedString(@"收到的礼物")])
    {
        UserInfoGiftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[UserInfoGiftTableViewCell className]];
        [cell setModel:_logic.model];
        return cell;
    }
    
    if([cellName isEqualToString:ASLocalizedString(@"小视频")])
    {
        UserinfoVideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[UserinfoVideoTableViewCell className]];
        cell.delegate = self;
        [cell setModel:_logic.model];
        return cell;
    }
    
    if([cellName isEqualToString:ASLocalizedString(@"私照")])
    {
        UserPhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[UserPhotoTableViewCell className]];
        [cell setModel:_logic.model];
        NSLog(@"%@",_logic.model.pictures[0].img);
        return cell;
    }
    
    if([cellName isEqualToString:ASLocalizedString(@"用户印象")])
    {
        TagHeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[TagHeaderTableViewCell className]];
        return cell;
    }

//    自评形象
//    用户印象
    
//    if([cellName isEqualToString:ASLocalizedString(@"自评形象")])
//    {
//        TagListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[TagListTableViewCell className]];
//        cell.tagName.text = ASLocalizedString(@"自评形象");
//        return cell;
//    }
    
    if([cellName isEqualToString:ASLocalizedString(@"标签列表")])
    {
        TagListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[TagListTableViewCell className]];
        cell.model = _evaluateData[indexPath.row];
//        cell.tagName.text = ASLocalizedString(@"用户印象");

        return cell;
    }

    
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
    //    cell.cellData = _dataSource[indexPath.row];
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(_listArray.count != 0 && indexPath.section == _listArray.count - 1)
    {
        return;
    }
    NSString *cellname = _listArray[indexPath.section][indexPath.row];
    if([cellname isEqualToString:ASLocalizedString(@"私照")])
    {
        PrivatePhotosViewController *vc = [[PrivatePhotosViewController alloc] init];
        vc.touid = self.uid;
        vc.isHidenNaviBar = NO;
        [self.navigationController pushViewController:vc animated:NO];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}

- (void)handleBackEvent:(QMUIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)shareAction {
    //分享媒介数据源
    //    NSMutableArray *shareAry = @[@{kXMNShareImage:@"more_chat",
    //                            kXMNShareHighlightImage:@"more_chat_highlighted",
    //                            kXMNShareTitle:ASLocalizedString(@"私信和群")},
    //                          @{kXMNShareImage:@"more_weixin",
    //                            kXMNShareHighlightImage:@"more_weixin_highlighted",
    //                            kXMNShareTitle:ASLocalizedString(@"微信好友")},
    //                          @{kXMNShareImage:@"more_circlefriends",
    //                            kXMNShareHighlightImage:@"more_circlefriends_highlighted",
    //                            kXMNShareTitle:ASLocalizedString(@"朋友圈")},
    //                          @{kXMNShareImage:@"more_icon_zhifubao",
    //                            kXMNShareHighlightImage:@"more_icon_zhifubao_highlighted",
    //                            kXMNShareTitle:ASLocalizedString(@"支付宝好友")},
    //                          @{kXMNShareImage:@"more_icon_zhifubao_friend",
    //                            kXMNShareHighlightImage:@"more_icon_zhifubao_friend_highlighted",
    //                            kXMNShareTitle:ASLocalizedString(@"生活圈")},
    //                          @{kXMNShareImage:@"more_icon_qq",
    //                            kXMNShareHighlightImage:@"more_icon_qq_highlighted",
    //                            kXMNShareTitle:@"QQ"},
    //                          @{kXMNShareImage:@"more_icon_qzone",
    //                            kXMNShareHighlightImage:@"more_icon_qzone_highlighted",
    //                            kXMNShareTitle:ASLocalizedString(@"QQ空间")},
    //                          @{kXMNShareImage:@"more_mms",
    //                            kXMNShareHighlightImage:@"more_mms_highlighted",
    //                            kXMNShareTitle:ASLocalizedString(@"短信")},
    //                          @{kXMNShareImage:@"more_email",
    //                            kXMNShareHighlightImage:@"more_email_highlighted",
    //                            kXMNShareTitle:ASLocalizedString(@"邮件分享")},
    //                          @{kXMNShareImage:@"more_icon_cardbackground",
    //                            kXMNShareHighlightImage:@"more_icon_cardbackground_highlighted",
    //                            kXMNShareTitle:ASLocalizedString(@"设卡片背景")},
    //                          @{kXMNShareImage:@"more_icon_collection",
    //                            kXMNShareTitle:ASLocalizedString(@"收藏")},
    //                          @{kXMNShareImage:@"more_icon_topline",
    //                            kXMNShareTitle:ASLocalizedString(@"帮上头条")},
    //                          @{kXMNShareImage:@"more_icon_link",
    //                            kXMNShareTitle:ASLocalizedString(@"复制链接")},
    //                          @{kXMNShareImage:@"more_icon_report",
    //                            kXMNShareTitle:ASLocalizedString(@"举报")},
    //                          @{kXMNShareImage:@"more_icon_back",
    //                            kXMNShareTitle:ASLocalizedString(@"返回首页")}];
    
    
    //    //分享媒介数据源
    NSArray* shareAry = @[@{kXMNShareImage:@"more_weixin",
                            kXMNShareHighlightImage:@"more_weixin_highlighted",
                            kXMNShareTitle:ASLocalizedString(@"微信好友")},
                          @{kXMNShareImage:@"more_circlefriends",
                        kXMNShareHighlightImage:@"more_circlefriends_highlighted",
                            kXMNShareTitle:ASLocalizedString(@"朋友圈")},
                          
                          ];
    
    NSMutableArray *fullarr = [NSMutableArray arrayWithArray:shareAry];
    
    //如果是自己显示删除按钮
    //    if([self.model.uid isEqualToString:[Config getOwnID]])
    //    {
    //        [fullarr addObject:@{kXMNShareImage:@"ic_short_video_del",
    //                             kXMNShareHighlightImage:@"ic_short_video_del",
    //                             kXMNShareTitle:ASLocalizedString(@"删除")}];
    //    }
    
    //自定义头部
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 36)];
    headerView.backgroundColor = [UIColor clearColor];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 21, headerView.frame.size.width-32, 15)];
    label.textColor = [UIColor colorWithRed:94/255.0 green:94/255.0 blue:94/255.0 alpha:1.0];;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:15];
    label.text = ASLocalizedString(@"操作");
    [headerView addSubview:label];
    
    XMNShareView *shareView = [[XMNShareView alloc] init];
    //设置头部View 如果不设置则不显示头部
    shareView.headerView = headerView;
    
    __weak __typeof(shareView)weakshareView = shareView;
    
    [shareView setSelectedBlock:^(NSUInteger tag, NSString *title) {
        if([title isEqualToString:ASLocalizedString(@"复制链接")])
        {
//            [self copyUrl];
        }
        else if([title isEqualToString:ASLocalizedString(@"删除")])
        {
//            [self stopVideoPreview:YES];
//            [self delVideo];
        }
        else if([title isEqualToString:@"QQ"])
        {
            //            [self simplyShare:SSDKPlatformSubTypeQQFriend];
        }
        else if([title isEqualToString:ASLocalizedString(@"QQ空间")])
        {
            //            [self simplyShare:SSDKPlatformSubTypeQZone];
            
            
        }
        else if([title isEqualToString:ASLocalizedString(@"微信好友")] || [title isEqualToString:ASLocalizedString(@"朋友圈")])
        {
            ShareView *shareView = [ShareView getView];
            shareView.nickname.text = _logic.model.user_nickname;
            [shareView.headerImage sd_setImageWithURL:safeurl(_logic.model.avatar)];
            shareView.frame = self.view.bounds;
            
            
            CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
            // 滤镜恢复默认设置
            [filter setDefaults];
            
            // 2. 给滤镜添加数据
            NSString *string = [NSString stringWithFormat:@"%@/mapi/public/index.php/api/download_api/index?invite_code=%@",URL_main,curUser.id];
            NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

            [filter setValue:data forKeyPath:@"inputMessage"];
            
            // 3. 生成二维码
            CIImage *image = [filter outputImage];
    
            shareView.QR.image =   [self createNonInterpolatedUIImageFormCIImage:image withSize:150];
            
            [self.view addSubview:shareView];
    
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [shareView removeFromSuperview];
                //            shareView.frame = CGRectMake(0, 0,872,1634);
                UIImage *imagevc = [self convertViewToImage:shareView];
                if([title isEqualToString:ASLocalizedString(@"朋友圈")])
                {
                    [[ShareManager sharedShareManager] shareImageToPlatformType:UMSocialPlatformType_WechatTimeLine WidthImage:imagevc withVC:self];

                }
                else
                {
                    [[ShareManager sharedShareManager] shareImageToPlatformType:UMSocialPlatformType_WechatSession WidthImage:imagevc withVC:self];

                }
            });
            


        }
//        else if([title isEqualToString:ASLocalizedString(@"朋友圈")])
//        {
//            //            [self simplyShare:SSDKPlatformSubTypeWechatTimeline];
//        }
        else if([title isEqualToString:ASLocalizedString(@"举报")])
        {
            //            [self ReportView];
            
        }
        NSLog(@"\ntag :%lu  \ntitle :%@",(unsigned long)tag,title);
        [weakshareView dismissUseAnimated:NO];
    }];
    
    //计算高度 根据第一行显示的数量和总数,可以确定显示一行还是两行,最多显示2行
    [shareView setupShareViewWithItems:fullarr];
    
    [shareView showUseAnimated:YES];
}


- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}




//将UIView转成UIImage
-(UIImage*)convertViewToImage:(UIView*)view{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(view.bounds.size);
    CGContextRef currnetContext = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:currnetContext];
    // 从当前context中创建一个改变大小后的图片
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    return image;
}

//点击更多
-(void)clickMore
{
    QMUIAlertController *alertMore = [[QMUIAlertController alloc] initWithTitle:ASLocalizedString(@"操作")message:@"" preferredStyle:QMUIAlertControllerStyleActionSheet];
    
    NSString *blackName = (_logic.model.is_black==0) ? ASLocalizedString(@"加入黑名单"):ASLocalizedString(@"解除拉黑");
    [alertMore addAction:[QMUIAlertAction actionWithTitle:blackName style:QMUIAlertActionStyleDefault handler:^(QMUIAlertAction *action) {
        [self addBlackList];
    }]];
    
    [alertMore addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"举报该用户")style:QMUIAlertActionStyleDefault handler:^(QMUIAlertAction *action) {
        ReportViewController *report = [[ReportViewController alloc] init];
        report.title = ASLocalizedString(@"举报");
        [self.navigationController pushViewController:report animated:YES];
    }]];
    
    [alertMore addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"取消")style:QMUIAlertActionStyleCancel handler:^(QMUIAlertAction *action) {
        
    }]];
    
    [alertMore showWithAnimated:YES];
    
}

//点击观看视频
-(void)UserPageInfoModelClickVideo:(videoListModel *)video
{
    
    //检查视频是否扣费
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"short_video_api" A:@"get_video"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:curUser.id forKey:@"uid"];
    [param setObject:StringFromInt(video.id) forKey:@"video_id"];
    [[HUDHelper sharedInstance] syncStopLoading];
    [CYNET POSTv3:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [self goVideoViewWithModel:video];
    } failure:^(NSString *error,NSInteger errCode) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [MBProgressHUD showTopTipMessage:error];
        
        if(errCode == 10020)
        {
            NSString *buyTip = [NSString stringWithFormat:ASLocalizedString(@"此视频为付费视频，需要消耗%@%@，是否购买"),video.coin,KCOIN_NAME];
            QMUIAlertController *alert = [[QMUIAlertController alloc] initWithTitle:ASLocalizedString(@"提示")message:buyTip preferredStyle:QMUIAlertControllerStyleAlert];
            [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"取消")style:QMUIAlertActionStyleCancel handler:^(QMUIAlertAction *action) {
                
            }]];
            
            [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"购买")style:QMUIAlertActionStyleDefault handler:^(QMUIAlertAction *action) {
                [self buyVideoViewWithModel:video];
            }]];
            [alert showWithAnimated:YES];
            return;
        }
        
    } hasCache:NO];
    
    
    
    return;
    if(video.status == 2 && video.type == 0)
    {
        
        NSString *buyTip = [NSString stringWithFormat:ASLocalizedString(@"此视频为付费视频，需要消耗%@%@，是否购买"),video.coin,KCOIN_NAME];
        QMUIAlertController *alert = [[QMUIAlertController alloc] initWithTitle:ASLocalizedString(@"提示")message:buyTip preferredStyle:QMUIAlertControllerStyleAlert];
        [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"取消")style:QMUIAlertActionStyleCancel handler:^(QMUIAlertAction *action) {
            
        }]];
        
        [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"购买")style:QMUIAlertActionStyleDefault handler:^(QMUIAlertAction *action) {
            [self buyVideoViewWithModel:video];
        }]];
        [alert showWithAnimated:YES];
        return;
    }
    else
    {
        [self goVideoViewWithModel:video];
    }
}


//todo 待封装
-(void)buyVideoViewWithModel:(videoListModel *)model
{
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"short_video_api" A:@"buy_video"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [[HUDHelper sharedInstance] syncLoading];
    [param setObject:StringFromInt(model.id) forKey:@"video_id"];
    
    [CYNET POSTv2:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [self goVideoViewWithModel:model];
    } failure:^(NSString *error) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [MBProgressHUD showTopTipMessage:error];
    } hasCache:NO];
    
}

-(void)goVideoViewWithModel:(videoListModel *)model
{
    VideoPlayViewController *vc = [[VideoPlayViewController alloc] init];
    vc.model = model;
    vc.videoList = @[model];
    vc.model.avatar = _logic.model.avatar;
    vc.currentIndex = 0;
    [self.navigationController pushViewController:vc animated:YES];
}


-(void)addBlackList
{
    [[HUDHelper sharedInstance] tipMessage:ASLocalizedString(@"拉黑成功")];
//    http://192.168.0.109/mapi/public/index.php/api/personal_api/black_user?uid=100114&token=0a846a208621426c5377e383b0ddabca&to_user_id=100114
    
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"personal_api" A:@"black_user"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:SafeStr(self.uid) forKey:@"to_user_id"];
    
    [CYNET POSTv2:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        [[HUDHelper sharedInstance] tipMessage:ASLocalizedString(@"操作成功")];
        [_logic loadData];

    } failure:^(NSString *error) {
        [MBProgressHUD showTopTipMessage:error];
    } hasCache:NO];
    
}


@end
